
const fs = require('fs')

class InputFileSystemAdapter {
  constructor (fsImpl) {
    this.fsImpl = fsImpl
  }
}

const fsMethods = [
  'stat',
  'statSync',
  'readFile',
  'readFileSync',
  'readlink',
  'readlinkSync',
  'readdir',
  'readdirSync'
]

for(const key of fsMethods) {
  Object.defineProperty(InputFileSystemAdapter.prototype, key, {
    configurable: true,
    writable: true,
    value: function (path) {
      if (typeof path === 'string') {
        if (path.indexOf('/memfs') !== 0) {
          // 磁盘查找
          return fs[key].apply(fs, arguments)
        }
        else if (path.indexOf('/node_modules/') !== -1) {
          // 磁盘查找
          const projectDir = process.cwd()
          arguments[0] = path.replace(/.*\/node_modules/, projectDir + '/node_modules')
          return fs[key].apply(fs, arguments)
        }
      }
      return this.fsImpl[key].apply(this.fsImpl, arguments)
    }
  })
}

module.exports = InputFileSystemAdapter
